import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {HttpService} from '../core/http.service';
import {StorageUtil} from '../utils/storage.util';
import {Http, HTTP_BASE_URL, JM_LOGIN_PATH, SERVERS_NAME, WEB_URL_SOCKET} from '../config/config';
import {UserInfo} from './domain/User';
import {AppReuseStrategy} from '../core/AppReuseStrategy';
import {PlatformLocation} from '@angular/common';
import {CommunicateService} from '../core/commuicate.service';
import {StatusEnum} from '../core/enum/status.enum';
import {NewsService} from './plat-manage/news/news.service';
import {WebsocketService} from '../utils/websocketService';
import {HttpClient} from '@angular/common/http';
import {Title} from '@angular/platform-browser';

declare var $: any;

@Component({
  selector: 'app-pages',
  templateUrl: './pages.component.html',
  styleUrls: ['./pages.component.css'],
  providers: [NewsService]
})
export class PagesComponent implements OnInit, OnDestroy {
  isCollapsed = false; // 收缩图标
  width = 220;
  subMenuList: any[] = [];
  // 自定义 trigger，设置为 null 时隐藏 trigger
  triggerTemplate = null;

  user: UserInfo = new UserInfo();

  // 当前选择菜单key
  toKey = '';
  // 头像
  imgUrl = '';

  titles = [];
  countNum = 0; // 计算箭头移动的位置
  angleShow = false; // 让小三角形隐藏显示
  navList: string[] = [];
  locationUrl = '';
  menuObj: RouterEntity = new RouterEntity();
  key: boolean;
  refreshTimer?: NodeJS.Timer; // 判断列表是否刷新定时器
  unReadList: Array<any> = []; // 未读消息列表
  readState = false;
  isShowGlobalInfo = false;
  alertInfoContent: any;
  private ws: WebSocket;
  receptVal: any;
  // test
  messages = [];
  connection: any;
  message: any;
  isShowDetail = false;
  // 查看消息数据实体
  lookNews: LookView = new LookView();
  // 单个已读id
  private subId: string | undefined;
  showKey = false;
  globalTitle = '';
  loginImage: '';
  // 默认总条数
  totalInfos = 0;

  constructor(private router: Router,
              private http: HttpService,
              private httpClient: HttpClient,
              private service: NewsService,
              private activatedRoute: ActivatedRoute,
              private communicate: CommunicateService,
              private location: PlatformLocation,
              private titleService: Title,
              private webService: WebsocketService) {
    // 获取系统信息
    activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.toKey) {
        this.toKey = queryParams.toKey;
      }
    });
  }

  ngOnDestroy() {
    this.key = false;
    // this.connection.unsubscribe();    // 组件销毁取消订阅
  }

  ngOnInit() {
    this.httpClient.get('assets/systemInfo.json').subscribe(res => {
      if (res['status'.toString()] === StatusEnum.SUCCESS) {
        this.loginImage = res['datas'.toString()]['loginImg'.toString()];
        this.globalTitle = res['datas'.toString()]['systemName'.toString()];
        this.titleService.setTitle(res['datas'.toString()]['indexTitle'.toString()]);
      }
    });
    // 初始获取弹窗信息
    // this.getAlertInfo();
    // 创建socket链接
    if ('WebSocket' in window) {
      // 建立websocket实时通讯机制
      // this.getWebInfo();
    } else {
      alert('current browse Not support websocket');
    }

    // 跳转到特定页面
    this.key = true;
    this.communicate.getMessage().subscribe(mes => {
      if (mes && mes.isShowParam === 1) {
        this.goToDetailMenu({url: mes.url}, 3);
      }
      if (mes && mes.openDetails) { // 我的实训室传消息，打开定时器
        this.startRefresh();
      }
    });
    // 取出当前登录用户
    this.user = StorageUtil.getLocalStorage('user');
    const token = StorageUtil.getLocalStorage('token');
    if (!token) {
      // this.router.navigate(['/login']);
      window.open(JM_LOGIN_PATH, '_self');
      return;
    }
    this.subMenuList = StorageUtil.getLocalStorage('menu');
    if (StorageUtil.getLocalStorage('toKey')) {
      this.toKey = StorageUtil.getLocalStorage('toKey');
    }

    // 判断是否存在指定到的菜单key
    if (!this.toKey) {
      if (this.subMenuList && this.subMenuList.length > 0) {
        if (this.subMenuList[0].children && this.subMenuList[0].children.length > 0) {
          this.subMenuList[0].children[0].checkStatus = true;
          StorageUtil.setLocalStorage('toKey', this.subMenuList[0].children[0].key);
        } else {
          this.subMenuList[0].checkStatus = true;
          StorageUtil.setLocalStorage('toKey', this.subMenuList[0].key);
        }
      }
    } else {
      StorageUtil.setLocalStorage('toKey', this.toKey);
      this.goToDetailMenu({key: this.toKey}, 2);
    }
    if (this.user && this.user.photo) {
      this.imgUrl = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER
      + 'source/view/' + this.user.photo.moduleName + '/' + this.user.photo.fileNewName}`;
    } else {
      this.imgUrl = 'assets/user/photo1.png';
      // if (!this.user.teacher.sex) {
      //   this.imgUrl = 'assets/user/photo0.png';
      // } else {
      //   this.imgUrl = 'assets/user/photo1.png';
      // }
    }

    if (StorageUtil.getLocalStorage('navList')) {
      this.navList = StorageUtil.getLocalStorage('navList');
    }
    if (!this.titles || this.titles.length === 0) {
      for (const i in this.location) {
        if (i === 'location') {
          this.locationUrl = this.getCaption(this.location[i].href);
          break;
        }
      }
      if (this.menuObj && this.menuObj.children && this.menuObj.children.length > 0) {
        this.getUrl(this.menuObj.children, this.locationUrl);
      }
    }

    // 浏览器窗口切换事件
    if (document.hidden !== undefined) {
      document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
          // console.log('离开')
        } else {
          // console.log('进入')
          // 取出当前登录用户
          const currUser = StorageUtil.getLocalStorage('user');
          if (!currUser || currUser.id !== this.user.id) {
            location.reload();
          }
        }
      });
    }
  }


  /**
   * 创建socket链接函数
   */
  getWebInfo() {
    const user = StorageUtil.getLocalStorage('user');
    const {id} = user.teacher;
    const webUrl = `${WEB_URL_SOCKET}`;
    const str = `/topic/${id}`;
    this.webService.getBySocket(webUrl, str, (res) => {
      // 判断是否是弹窗消息还是列表消息
      if (res) {
        if (res.eject === 1) {
          this.alertInfoContent = res;
          this.isShowGlobalInfo = true; // 显示
        } else {
          this.readState = true;
          if (this.unReadList.length < 5) {
            this.unReadList.unshift(res); // 推入列表栈
          } else {
            this.unReadList.pop(); // 去掉最后一个
            this.unReadList.unshift(res); // 推入列表栈
          }
          this.isShowGlobalInfo = false;
        }
      }
    });
  }

  /**
   * 获取弹窗消息
   */
  getAlertInfo(): void {
    this.http.get({}, `${SERVERS_NAME.SECURITY_SERVER}sys/message/checkMsg`).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        if (res.datas) {
          if (res.datas.firstEject) {
            this.alertInfoContent = res.datas.firstEject;
            this.isShowGlobalInfo = true;
          } else {
            this.isShowGlobalInfo = false;
          }
          this.readState = res.datas.hasRead;
        }
      }
    });
  }

  /**
   * 点击获取小铃铛未读消息
   */
  getListUnread(): void {
    this.http.get({}, `${SERVERS_NAME.SECURITY_SERVER}sys/message/listUnread`).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.showKey = true;
        (res.datas && res.datas.data.length) ? ((this.unReadList = res.datas.data) && (this.totalInfos = res.datas.totalRecords) && (this.readState = true))
          : ((this.unReadList = []) && (this.totalInfos = 0) && (this.readState = false));
        this.unReadList.length ? this.readState = true : this.readState = false;
      }
    });
  }

  /**
   * 全部已读消息
   */
  allHasRead(): void {
    const Ids: Array<string> = this.dealGetIds();
    this.dealHasRead(Ids);
  }

  /**
   * 已读函数
   * @param idArr:sub ids
   */
  dealHasRead(idArr: Array<string>): void {
    this.service.signReadList(idArr, 'signRead').subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.getListUnread(); // 重新获取未读消息列表
      }
    });
  }

  /**
   * 点击查看详情
   * @param data:数据源
   */
  showInfoFn(data: any): void {
    this.subId = data.id;
    this.isShowDetail = true;
    this.showKey = false;
    this.lookNews = {
      senderName: data.senderName,
      content: data.content,
      gmtCreate: data.gmtCreate,
      title: data.title,
    };
  }

  closeFn() {
    // e.stopPropagation();
    // e.preventDefault();
    this.isShowDetail = false;
    this.showKey = true;
    this.dealHasRead([this.subId]);

  }

  /**
   * 处理获取全部已读id
   */
  dealGetIds(): Array<string> {
    const arr: Array<string> = [];
    this.unReadList.forEach(item => {
      arr.push(item.id);
    });
    return arr;
  }

  infoAlert(): string {
    if (this.unReadList === []) {
      return '暂无未读消息';
    }
  }

  /**
   *跳转到消息中心
   */
  toAllInfo(): void {
    this.showKey = false;
    // this.readState = true;
    AppReuseStrategy.deleteRouteSnapshot('/pages/plat/news');
    this.router.navigate(['/pages/plat/news']);
  }

  /**
   * 点击跳转对应的模块页面
   * @param data:数据源
   */
  clickJump(data: any): void {
    this.showKey = false;
    this.isShowDetail = false;
    const keyStr: string = data.redirectUrl;
    let toUrl = '';
    let routerKey = '';
    const subscribeId: string = data.targetId; // 跳转预约模块所需id
    let useType = '1'; // 预约类型 1--个人，2-团队
    switch (keyStr) {
      case 'personal_subscribe_view':
        toUrl = `/pages/appointment-system/appointment-record`;
        useType = '1'; // 个人
        this.dealSubscribeJump(toUrl, subscribeId, useType);
        break;
      case 'team_subscribe_view':
        toUrl = `/pages/appointment-system/appointment-record`;
        useType = '2'; // 团队
        this.dealSubscribeJump(toUrl, subscribeId, useType);
        break;
      case 'tch_safety_exam':
        toUrl = `/pages/safety-education/safety-examination`;
        routerKey = '1';
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'tch_safety_learn_task':
        toUrl = `/pages/safety-education/learn-tasks`;
        routerKey = '2'; // 消息中心跳转标识
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'tch_classroom_learn_task':
        toUrl = `/pages/safety-education/learn-tasks`;
        routerKey = '2'; // 消息中心跳转标识
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'tch_ask_leave_approve':
        console.log('前往审批到请假管理');
        this.message.warning('请假管理系统暂未开放,不能跳转');
        break;
      case 'tch_ask_leave_view':
        // this.dealDefaultJump(toUrl,routerKey);
        this.message.warning('请假管理系统暂未开放,不能跳转');
        console.log('查看请假-到请假管理');
        break;
      case 'tch_repeal_approve':
        toUrl = `/pages/appointment-system/approval`;
        routerKey = '2'; // 撤销审批标识
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'tch_subscribe_approve':
        toUrl = `/pages/appointment-system/approval`;
        routerKey = '1'; // 预约审批标识
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'tch_break_promise_personal_view':
        toUrl = `/pages/appointment-system/default-record`;
        routerKey = '1'; // 个人
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'tch_break_promise_team_view':
        toUrl = `/pages/appointment-system/default-record`;
        routerKey = '2'; // 团队
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'stu_break_promise_personal_view':
        toUrl = `/pages/appointment-system/default-record`;
        routerKey = '1'; // 团队
        this.dealDefaultJump(toUrl, routerKey);
        break;
      case 'stu_break_promise_team_view':
        toUrl = `/pages/appointment-system/default-record`;
        routerKey = '2'; // 团队
        this.dealDefaultJump(toUrl, routerKey);
        break;
      default:
        break;

    }

  }

  /**
   * 简单模块跳转
   * @param toUrl:targetUrl
   * @param routerKey:key
   */
  dealDefaultJump(toUrl: string, routerKey: string): void {
    AppReuseStrategy.deleteRouteSnapshot(toUrl);
    // 携带控制参数跳转
    this.router.navigate([toUrl], {
      queryParams: {
        homeId: routerKey
      }
    });
  }

  /**
   * 消息点击跳转预约模块详情处理函数
   * @param toUrl:targetUrl
   * @param subscribeId:targetId
   * @param useType:subscribeType
   */
  dealSubscribeJump(toUrl: string, subscribeId: string, useType: string): void {
    AppReuseStrategy.deleteRouteSnapshot(toUrl);
    // 携带控制参数跳转
    this.router.navigate([toUrl], {
      queryParams: {
        id: subscribeId,
        useType,
      }
    });
  }

  /**
   * 点击知道了确认当前数据已读
   */
  hasKnown(): void {
    const idArr: Array<string> = [this.alertInfoContent.id];
    this.service.signReadList(idArr, 'signRead').subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.isShowGlobalInfo = false;
      }
    });
  }

  /**
   * 我的实训室----定时器获取刷新参数
   */
  startRefresh() {
    if (!this.refreshTimer) {
      this.refreshTimer = setInterval(() => { // 一秒钟调用一次
        const openMenu = StorageUtil.getLocalStorage('isOpenMenu');
        const openMenuUrl = StorageUtil.getLocalStorage('openMenuUrl');
        if (openMenu) {
          clearInterval(this.refreshTimer);
          this.refreshTimer = null;
          StorageUtil.setLocalStorage('isOpenMenu', false);
          StorageUtil.setLocalStorage('openMenuUrl', null);
          this.goToDetailMenu({url: openMenuUrl}, 3);
        }
      }, 1000);
    }
  }

  /**
   * 菜单收缩
   */
  openHandler(num, level) {
    this.subMenuList.forEach((item, index) => {
      if (level === 1) {
        item.disabled = false;
        if (num === index) {
          item.disabled = true;
        }
      } else {
        item.children.forEach((temp, p) => {
          if (level === 2) {
            temp.disabled = false;
            if (num === p) {
              temp.disabled = true;
            }
          } else {
            temp.children.forEach((task, n) => {
              task.disabled = false;
              if (num === n) {
                task.disabled = true;
              }
            });
          }
        });
      }
    });
  }

  /**
   * 点击跳到指定页面
   * @param obj:本身点击
   * @param num:1本身点击
   */
  goToDetailMenu(obj, num) {
    if (obj.targetType === 2) { // 2第三方链接 0,1内部系统打开
      window.open(obj.url);
      return;
    }
    if (obj.url !== '/pages/home') {
      AppReuseStrategy.deleteRouteSnapshot('/pages/home');
    }
    if (this.titles.length === 0) {
      AppReuseStrategy.resetCache();
    }
    if (num === 1) {
      // 实训室可视化
      if (obj.title === '实训室可视化') {
        StorageUtil.setLocalStorage('isOpenMenu', false); // 向上一级一页发送刷新消息
        this.startRefresh();
        window.open('#/trainroom-visual');
      } else {

        // 先清除当前路由，在重新加载，实现点击刷新菜单数据--开始
        this.titles.forEach((item, index) => {
          if (item.url === obj.url) {
            AppReuseStrategy.deleteRouteSnapshot(item.url);
          }
        });
        // 先清除当前路由，在重新加载，实现点击刷新菜单数据--结束

        this.router.navigate([obj.url]);
        this.getAllMenuStatus(this.subMenuList, obj, num);
        // 点击菜单去除其他跳转菜单传递的参数
        this.communicate.sendMessage({
          isShowParam: 2
        });

      }
    } else if (num === 2) {
      this.getAllMenuStatus(this.subMenuList, obj, num);
      // 点击菜单去除其他跳转菜单传递的参数
      this.communicate.sendMessage({
        isShowParam: 2
      });
    } else {
      this.router.navigate([obj.url]);
      this.getAllMenuStatus(this.subMenuList, obj, num);
    }


    if (num === 1) {
      if (this.navList && this.navList.length === 0) {
        this.navList[0] = obj.title;
      } else {
        this.navList[obj.level] = obj.title;
      }
      const len = this.navList.length;
      this.navList.splice(obj.level + 1, len - obj.level);
      StorageUtil.setLocalStorage('navList', this.navList);

      // 实训室可视化
      if (obj.title === '实训室可视化') {

      } else {
        const result = this.titles.some(item => {
          if (item.url === obj.url) {
            return true;
          }
        });
        if (!result) {
          this.titles.push({name: obj.title, url: obj.url, key: obj.key, checkStatus: obj.checkStatus});
        }
      }
      this.setChecked(obj.url);
      if ($('.infoCover').height() > $('.navInfo').height()) {
        this.angleShow = true;
      }
    }

    StorageUtil.setLocalStorage('menu', this.subMenuList);
    this.subMenuList.forEach(item => {
      item.children.forEach(temp => {
        if (obj.url === temp.url) {
          this.menuObj = item;
        }
      });
    });
  }

  /**
   * 遍历树
   * @param datas:树
   * @param obj:obj-当前传递的对象
   * @param num:123
   */
  getAllMenuStatus(datas, obj, num) {
    if (num !== 3) {
      for (const key in datas) {
        // 后台正式返回菜单后url改成其他key值
        if (datas[key].key === obj.key) {
          datas[key].checkStatus = true;
        } else {
          datas[key].checkStatus = false;
          this.getAllMenuStatus(datas[key].children, obj, num);
        }
      }
    } else {
      for (const key in datas) {
        if (datas[key].url === obj.url) {
          datas[key].checkStatus = true;
          this.goToDetailMenu(datas[key], 1);
        } else {
          datas[key].checkStatus = false;
          this.getAllMenuStatus(datas[key].children, obj, num);
        }
      }
    }
  }

  /**
   * 设置其他为未选中状态
   * @param url:url
   */
  setChecked(url: string): void {
    this.titles.map(e => {
        if (e.url === url) {
          e.checkStatus = true;
        } else {
          e.checkStatus = false;
        }
        return e;
      }
    );
  }

  /**
   * tab 点击
   * @param obj：数据
   */
  navUrl(obj): void {
    this.router.navigate([obj.url]);
    this.setChecked(obj.url);
    this.getAllMenuStatus(this.subMenuList, obj, 1);
  }

  /**
   * tab 关闭
   */
  closeNav(url: string, index: number): void {
    this.titles.splice(index, 1);
    AppReuseStrategy.deleteRouteSnapshot(url);
    if (this.titles.length === 0) {
      StorageUtil.setLocalStorage('navList', []);
      this.router.navigate(['pages/home']);
      return;
    } else {
      const preUrl = this.titles[this.titles.length - 1].url;
      this.setChecked(preUrl);
      this.getAllMenuStatus(this.subMenuList, this.titles[this.titles.length - 1], 1);
      this.router.navigate([preUrl]);
    }
  }

  /**
   * 点击nav左侧小三角
   */
  clickLeft() {
    const child = $('.infoCover');
    if (this.countNum >= 1) {
      child[0].style.left = parseInt(child[0].style.left, 10) + 200 + 'px';
      this.countNum--;
    }
  }

  /**
   * 点击nav右侧小三角
   */
  clickRight() {
    const par = $('.navInfo').height();
    const child = $('.infoCover');
    if (child.height() > par) {
      this.countNum++;
      child[0].style.left = '-' + this.countNum * 200 + 'px';
    }
  }


  /**
   * 截取字符串
   * @param obj:数据
   */
  getCaption(obj) {
    const index = obj.lastIndexOf('\#');
    obj = obj.substring(index + 1, obj.length);
    return obj;
  }

  /**
   * 遍历
   * @param datas:树
   * @param urls：url
   */
  getUrl(datas, urls) {
    for (const val in datas) {
      if (datas[val].url === urls) {
        this.titles.push({name: datas[val].title, key: datas[val].key, url: datas[val].url, checkStatus: true});
      } else {
        this.getUrl(datas[val].children, urls);
      }
    }
  }

  /**
   * 首页点击
   */
  homeClick() {
    // StorageUtil.setLocalStorage('navList', []);
    // this.titles = [];
    this.setChecked('pages/home');
    this.router.navigate(['pages/home']);
  }

  /**
   * 关闭标签左侧
   * @param num:1-当前，2-其他，3-所有
   */
  closeNavMenu(num) {
    for (const i in this.location) {
      if (i === 'location') {
        this.locationUrl = this.getCaption(this.location[i].href);
        break;
      }
    }
    if (num === 1) {
      this.titles.forEach((item, index) => {
        if (item.url === this.locationUrl) {
          this.closeNav(item.url, index);
          AppReuseStrategy.deleteRouteSnapshot(item.url);
        }
      });
    } else if (num === 2) {
      const arr = [];
      this.titles.forEach(item => {
        if (item.url === this.locationUrl) {
          arr.push(item);
        } else {
          AppReuseStrategy.deleteRouteSnapshot(item.url);
        }
      });
      this.titles = arr;
    } else {
      StorageUtil.setLocalStorage('navList', []);
      this.titles = [];
      AppReuseStrategy.resetCache();
      this.homeClick();
    }
  }

  /**
   * 个人中心点击
   */
  personalClick() {
    this.router.navigate(['/pages/personal-center']);
  }

  /**
   * 退出登录
   */
  loginOut() {
    this.key = false;
    const userObj = StorageUtil.getLocalStorage('cryObj');
    StorageUtil.clearSession();
    StorageUtil.clearLocal();
    if (userObj && userObj !== {}) {
      StorageUtil.setLocalStorage('cryObj', userObj);  // 存回浏览器
    }
    AppReuseStrategy.resetCache();
    AppReuseStrategy.deleteRouteSnapshot('/pages');
    AppReuseStrategy.deleteRouteSnapshot('/pages/home');
    AppReuseStrategy.deleteRouteSnapshot('/pages/personal-center');
    // this.router.navigate(['/login']);
    window.open(JM_LOGIN_PATH, '_self');
  }

}

export class RouterEntity {
  title?: string;
  url?: string;
  key?: string;
  value?: number;
  children?: any[];
}

/**
 * 查看详细信息
 */
class LookView {
  senderName: string | undefined;
  gmtCreate: string | undefined;
  content: string | undefined;
  title: string | undefined;
}
